//
//  ViewController.m
//  myhuibao
//
//  Created by lijun on 13-2-4.
//  Copyright (c) 2013年 myhuibao. All rights reserved.
//

#import "HouseViewController.h"
#import "BoxSearchViewController.h"
#import "ASIHTTPRequest.h"
//#import "ASIFormDataRequest.h"
#import "SBJson.h"
#import<QuartzCore/QuartzCore.h>
#import "Config.h"
#import "OMGToast.h"
#import "RequestLoadingView.h"

@interface HouseViewController ()
@property (nonatomic, strong) PMCalendarController *pmCC;

@end

@implementation HouseViewController
@synthesize tbBoxSize;
@synthesize tbTime;
@synthesize tbDate;
@synthesize tbArea;
@synthesize tbCity;
@synthesize mainView;
@synthesize btBack;
@synthesize tbBoxType;
@synthesize pmCC;
@synthesize reqCity;
@synthesize reqArea;
@synthesize reqDiningTime;
@synthesize reqBoxType;
@synthesize reqCapacity;
@synthesize reqConsume;
@synthesize reqCuisine;
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    [self initDefault];
    
    [self startRequest];

    arrayDiningTime = [NSMutableArray arrayWithObjects:
                      [NSDictionary dictionaryWithObjectsAndKeys:@"中餐",@"timeDesc", @"2",@"timeID",nil],
                      [NSDictionary dictionaryWithObjectsAndKeys:@"晚餐",@"timeDesc", @"4",@"timeID",nil],
                      nil];
}
-(void)viewDidAppear:(BOOL)animated
{
    if ([[Config Instance]getCityId]!=cityId) {
        [self getArea];
    }
}

- (void)startRequest
{

    if(!loadingView)
    {
        loadingView = [[RequestLoadingView alloc]
                             initRequestLoadingView:self
                              queueFinishSelector:nil
                                viewFrame:LoadingViewFrame];
    }
    [self getCity];
    [self getArea];
    [self getBoxType];
    [self getCapacity];
    
    [loadingView addRequestToQueue:reqCity];
    [loadingView addRequestToQueue:reqArea];
    [loadingView addRequestToQueue:reqBoxType];
    [loadingView addRequestToQueue:reqCapacity];
    
    [loadingView startRequestQueue];

}

- (void)initDefault{
    if(_showback==1)
        btBack.hidden = NO;
    else
        btBack.hidden = YES;
    //获取当前日期
    NSDate *curDate = [NSDate date];
    tbDate.text = [NSString stringWithFormat:@"选择日期：%@", [curDate dateStringWithFormat:@"yyyy-MM-dd"]];
    NSString *d = [curDate dateStringWithFormat:@"yyyy-MM-dd"];
    if (![diningDate isEqualToString:d]) {
        diningDate = [d copy];
    }
    //默认城市
    tbCity.text = [NSString stringWithFormat:@"城市：%@",[[Config Instance]getCity]];
    cityId = [[Config Instance]getCityId];
    //判读默认时间段
    if([[[NSDate date] dateStringWithFormat:@"HH"]intValue]<12)
    {
        diningTime = 2;_selectedIndex1=0;
        tbTime.text = [NSString stringWithFormat:@"选择时间：%@",@"中餐"];
    }else
    {
        diningTime = 4;_selectedIndex1=1;
        tbTime.text = [NSString stringWithFormat:@"选择时间：%@",@"晚餐"];
    }
    //默认商圈
    areaId = 0;
    //包厢类型
    boxType = 0;
    //包厢大小
    capacityId = 0;
    
    mainView.layer.cornerRadius=3;
    mainView.layer.borderWidth=1;
    mainView.layer.borderColor=LINE_COLOR.CGColor;
    [[mainView layer] setShadowOffset:CGSizeMake(1, 1)];
    [[mainView layer] setShadowRadius:1];
    [[mainView layer] setShadowOpacity:1];
    [[mainView layer] setShadowColor:LINE_COLOR.CGColor];
}
- (void) getCity{
    //异步请求
    NSURL *url = [NSURL URLWithString:url_city];
    reqCity = [ASIHTTPRequest requestWithURL:url];
    [reqCity setDidFinishSelector:@selector(finishCity:)];
    isCityFinished = false;
    [reqCity setShouldAttemptPersistentConnection:NO];
    [reqCity setDelegate: self];
    
    if (!loadingView.bFirstRequest) {
        [reqCity startAsynchronous];
    }
    
}
- (void) getArea{
    //异步请求
//    NSDictionary *dic =[arrayCity objectAtIndex:0];
//    cityId = [[dic valueForKey:@"cityID"] intValue];
    cityId = [[Config Instance] getCityId];
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?cityID=%d",url_areaWithDistrict,cityId]] ;
    reqArea = [ASIHTTPRequest requestWithURL:url];
    [reqArea setDidFinishSelector:@selector(finishArea:)];
    isAreaFinished = false;
    [reqArea setShouldAttemptPersistentConnection:NO];
    [reqArea setDelegate: self];
    
    
    if (!loadingView.bFirstRequest) {
        [reqArea startAsynchronous];
    }

}
- (void) getDiningTime{
    //异步请求
    NSURL *url = [NSURL URLWithString:url_diningTime];
    reqDiningTime = [ASIHTTPRequest requestWithURL:url];
    [reqDiningTime setDidFinishSelector:@selector(finishDiningTime:)];
    isDiningTimeFinished = false;
    [reqDiningTime setShouldAttemptPersistentConnection:NO];
    [reqDiningTime setDelegate: self];
    [reqDiningTime startAsynchronous];
    
}
- (void) getBoxType{
    //异步请求
    NSURL *url = [NSURL URLWithString:url_boxType];
    reqBoxType = [ASIHTTPRequest requestWithURL:url];
    [reqBoxType setDidFinishSelector:@selector(finishBoxType:)];
    isBoxTypeFinished = false;
    [reqBoxType setShouldAttemptPersistentConnection:NO];
    [reqBoxType setDelegate: self];
    
    if (!loadingView.bFirstRequest) {
        [reqBoxType startAsynchronous];
    }
    
}
- (void) getCapacity{
    //异步请求
    NSURL *url = [NSURL URLWithString:url_boxCapacity];
    reqCapacity = [ASIHTTPRequest requestWithURL:url];
    [reqCapacity setDidFinishSelector:@selector(finishCapacity:)];
    isCapacityFinished = false;
    [reqCapacity setShouldAttemptPersistentConnection:NO];
    [reqCapacity setDelegate: self];
    
    if (!loadingView.bFirstRequest) {
        [reqCapacity startAsynchronous];
    }

}
- (void)finishCity:(ASIHTTPRequest *)request
{
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    arrayCity = [dic valueForKey:@"data"];
    isCityFinished = true;
}
- (void)finishArea:(ASIHTTPRequest *)request
{
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    NSMutableArray *data = [dic valueForKey:@"data"];
    arrayDistrict = [[NSMutableArray alloc]init];
    for (int i=0;i<data.count;i++) {
//        NSDictionary *dic = data[i];
//        NSString *county = [dic valueForKey:@"county"];
//        NSString *countyCode=[county componentsSeparatedByString:@"-"][0];
//        NSString *countyName=[county componentsSeparatedByString:@"-"][1];
        
        NSDictionary *dic = [data objectAtIndex:i];
        NSString *county = [dic valueForKey:@"county"];
        NSString *countyCode=[[county componentsSeparatedByString:@"-"] objectAtIndex:0];
        NSString *countyName=[[county componentsSeparatedByString:@"-"]objectAtIndex:1];
        
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                              countyCode,@"countyCode",countyName,@"countyName",[dic valueForKey:@"areaList"],@"areaList",nil];
        [arrayDistrict insertObject:dict atIndex:i];
    }
    //默认全部
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @"0",@"areaID",@"全部商圈",@"areaName",nil];
    arrayArea = [[NSMutableArray alloc]init];
    [arrayArea insertObject: dict atIndex:0];
    NSDictionary *all = [NSDictionary dictionaryWithObjectsAndKeys:
                         @"0",@"countyCode",@"全部商圈",@"countyName",arrayArea,@"areaList",nil];
    [arrayDistrict insertObject: all atIndex:0];
    isAreaFinished = true;
    areaId = 0;
    tbArea.text = @"选择商圈：不限";
    _selectedTypeIndex=0;
    _selectedIndex=0;
}
- (void)finishCapacity:(ASIHTTPRequest *)request
{
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    arrayCapacity = [dic valueForKey:@"data"];
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
            @"0",@"boxCapacityID",@"不限",@"boxCaptcityDesc",nil];
    [arrayCapacity insertObject: dict atIndex:0];
    isCapacityFinished = true;
}
- (void)finishDiningTime:(ASIHTTPRequest *)request
{
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    arrayDiningTime = [dic valueForKey:@"data"];
    isDiningTimeFinished = true;
}

//下面是两个代理函数,当数据请求成功时会调用requestFinished，请求失败时（如网络问题或服务器内部错误）会调用requestFailed
- (void)finishBoxType:(ASIHTTPRequest *)request
{
    // Use when fetching text data
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    arrayBoxType = [dic valueForKey:@"data"];
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @"0",@"boxTypeID",@"不限",@"boxTypeDesc",nil];
    [arrayBoxType insertObject: dict atIndex:0];
    isBoxTypeFinished = true;
//    NSLog(@"%@", arrayBoxType);
    //评论页面
//    NSURL *url = [NSURL URLWithString:url_city] ;
//    request = [ASIHTTPRequest requestWithURL:url];
//    [request startSynchronous];
//    jsonStr = [request responseString];
//    dic = [jsonStr JSONValue];
//    arrayCity = [dic valueForKey:@"data"];
//    
//    dic =[arrayCity objectAtIndex:0];
//    cityId = [[dic valueForKey:@"cityID"] intValue];
//    url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?cityID=%d",url_area,cityId]] ;
//    request = [ASIHTTPRequest requestWithURL:url];
//    [request startSynchronous];
//    jsonStr = [request responseString];
//    dic = [jsonStr JSONValue];
//    arrayArea = [dic valueForKey:@"data"];
//    dict = [NSDictionary dictionaryWithObjectsAndKeys:
//                          @"0",@"areaID",@"不限",@"areaName",nil];
//    [arrayArea insertObject: dict atIndex:0];
//    //    NSLog(@"%@",arrayArea);
//
//    url = [NSURL URLWithString:url_diningTime] ;
//    request = [ASIHTTPRequest requestWithURL:url];
//    [request startSynchronous];
//    jsonStr = [request responseString];
//    dic = [jsonStr JSONValue];
//    arrayDiningTime = [dic valueForKey:@"data"];
//    
//    url = [NSURL URLWithString:url_boxCapacity] ;
//    request = [ASIHTTPRequest requestWithURL:url];
//    [request startSynchronous];
//    jsonStr = [request responseString];
//    dic = [jsonStr JSONValue];
//    arrayCapacity = [dic valueForKey:@"data"];
//    dict = [NSDictionary dictionaryWithObjectsAndKeys:
//            @"0",@"boxCapacityID",@"不限",@"boxCaptcityDesc",nil];
//    [arrayCapacity insertObject: dict atIndex:0];
//
}
- (void) getCuisine
{
    NSURL *url = [NSURL URLWithString:url_cuisineListWithType] ;
    reqCuisine = [ASIHTTPRequest requestWithURL:url];
    [reqCuisine setDidFinishSelector:@selector(finishCuisine:)];
    [reqCuisine setShouldAttemptPersistentConnection:NO];
    reqCuisine.delegate = self;
    isCuisineFinished = false;
    [reqCuisine startAsynchronous];
}
- (void)finishCuisine:(ASIHTTPRequest *)request
{
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    //    arrayCuisine = [dic valueForKey:@"data"];
    //    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
    //                          @"0",@"cuisineID",@"不限",@"cuisineName",nil];
    //    [arrayCuisine insertObject: dict atIndex:0];
    NSMutableArray *data = [dic valueForKey:@"data"];
    arrayCuisineType = [[NSMutableArray alloc]init];
    for (int i=0;i<data.count;i++) {
        NSDictionary *dic = [data objectAtIndex:i];//data[i];
        NSString *cuisine = [dic valueForKey:@"cuisinesType"];
//        NSString *cuisineCode=[cuisine componentsSeparatedByString:@"-"][0];
//        NSString *cuisineName=[cuisine componentsSeparatedByString:@"-"][1];
        NSString *cuisineCode=[[cuisine componentsSeparatedByString:@"-"] objectAtIndex:0];
        NSString *cuisineName=[[cuisine componentsSeparatedByString:@"-"]objectAtIndex:1];
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                              cuisineCode,@"cuisineCode",cuisineName,@"cuisineName",[dic valueForKey:@"cuisinesList"],@"cuisinesList",nil];
        [arrayCuisineType insertObject:dict atIndex:i];
    }
    //默认全部
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @"0",@"cuisineID",@"全部菜系",@"cuisineName",nil];
    arrayCuisine = [[NSMutableArray alloc]init];
    [arrayCuisine insertObject: dict atIndex:0];
    NSDictionary *all = [NSDictionary dictionaryWithObjectsAndKeys:
                         @"0",@"cuisineCode",@"全部菜系",@"cuisineName",arrayCuisine,@"cuisinesList",nil];
    [arrayCuisineType insertObject: all atIndex:0];
    isCuisineFinished = true;
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",error);
    if (error.code==net_failure_code) {
        [OMGToast showWithText:net_failure_msg bottomOffset:100];
    }
}

- (void)viewDidUnload
{
    [self setTbBoxType:nil];
    [self setTbBoxSize:nil];
    [self setTbTime:nil];
    [self setTbDate:nil];
    [self setTbArea:nil];
    [self setTbCity:nil];
    [self setBtBack:nil];
    [self setMainView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title=@"包厢搜索";
    }
    return self;
}
- (IBAction)showBoxType:(id)sender {
    selectIndex = 5;
    LeveyPopListView *lplv = [[LeveyPopListView alloc] initWithTitle:@"请选择包厢类型" options:arrayBoxType];
    lplv.name = @"boxTypeDesc";
    lplv.selectedIndex = _selectedIndex3;
    lplv.delegate = self;
    [lplv showInView:self.view animated:YES];

}
#pragma mark - LeveyPopListView delegates
- (void)leveyPopListView:(LeveyPopListView *)popListView didSelectedIndex:(NSInteger)anIndex options:(NSArray *)_options didSelectedTypeIndex:(NSInteger)anTypeIndex
{
    switch (selectIndex) {
        case 1:{
            tbCity.text = [NSString stringWithFormat:@"城市： %@",[[arrayCity objectAtIndex:anIndex] objectForKey:@"cityName"]];
            cityId = [[[arrayCity objectAtIndex:anIndex] objectForKey:@"cityID"] intValue];
            [arrayArea removeAllObjects];
            [self getArea];
            break;}
        case 2:{
            _selectedIndex = anIndex;
            _selectedTypeIndex = anTypeIndex;
            arrayArea = [_options copy];
            tbArea.text = [NSString stringWithFormat:@"选择商圈：%@",[[_options objectAtIndex:anIndex] objectForKey:@"areaName"]];
            
            areaId = [[[_options objectAtIndex:anIndex] objectForKey:@"areaID"] intValue];
            break;}
        case 4:{
            _selectedIndex1 = anIndex;
            tbTime.text = [NSString stringWithFormat:@"选择时间：%@",[[arrayDiningTime objectAtIndex:anIndex] objectForKey:@"timeDesc"]];
            diningTime= [[[arrayDiningTime objectAtIndex:anIndex] objectForKey:@"timeID"] intValue];
            break;}
        case 5:{
            _selectedIndex3 = anIndex;

            tbBoxType.text = [NSString stringWithFormat:@"选择类型：%@",[[arrayBoxType objectAtIndex:anIndex] objectForKey:@"boxTypeDesc"]];
            boxType= [[[arrayBoxType objectAtIndex:anIndex] objectForKey:@"boxTypeID"] intValue];
            break;}
        case 6:{
            _selectedIndex2 = anIndex;

            tbBoxSize.text = [NSString stringWithFormat:@"选择大小：%@",[[arrayCapacity objectAtIndex:anIndex] objectForKey:@"boxCaptcityDesc"]];
            capacityId= [[[arrayCapacity objectAtIndex:anIndex] objectForKey:@"boxCapacityID"] intValue];
            break;}
        default:
            break;
    }
}
- (void)leveyPopListViewDidCancel
{
    //edtCity.text = @"You have cancelled";
}

- (IBAction)doBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)showCity:(id)sender {
    selectIndex = 1;
    LeveyPopListView *lplv = [[LeveyPopListView alloc] initWithTitle:@"请选择城市..." options:arrayCity fullHeight:72];
    lplv.name = @"cityName";
    lplv.delegate = self;
    [lplv showInView:self.view animated:YES];
}

- (IBAction)showArea:(id)sender {
//    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?cityID=%d",url_area,cityId]] ;
//    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
//    
//    [request setDelegate: self];
//    [request startSynchronous];
//    NSString *jsonStr = [request responseString];
//    NSDictionary *dic = [jsonStr JSONValue];
//    arrayArea = [dic valueForKey:@"data"];
//    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
//            @"0",@"areaID",@"不限",@"areaName",nil];
//    [arrayArea insertObject: dict atIndex:0];
    
    selectIndex = 2;
//    arrayArea = [arrayDistrict[_selectedTypeIndex] objectForKey:@"areaList"];
    arrayArea = [[arrayDistrict objectAtIndex: _selectedTypeIndex] objectForKey:@"areaList"];
LeveyPopListView *lplv = [[LeveyPopListView alloc] initWithTitle:@"请选择商圈" options:arrayArea types:arrayDistrict fullHeight:72];
    lplv.name = @"areaName";
    lplv.typeName = @"countyName";
    lplv.listName = @"areaList";
    lplv.selectedTypeIndex = _selectedTypeIndex;
    lplv.selectedIndex = _selectedIndex;
    lplv.delegate = self;
    [lplv showInView:self.view animated:YES];

}

- (IBAction)showDiningTime:(id)sender {
    selectIndex = 4;
    LeveyPopListView *lplv = [[LeveyPopListView alloc] initWithTitle:@"请选择就餐时间" options:arrayDiningTime];
    lplv.name = @"timeDesc";
    lplv.selectedIndex = _selectedIndex1;
    lplv.delegate = self;
    [lplv showInView:self.view animated:YES];
}

- (IBAction)showCapacity:(id)sender {
    selectIndex = 6;
    LeveyPopListView *lplv = [[LeveyPopListView alloc] initWithTitle:@"请选择包厢大小" options:arrayCapacity];
    lplv.name = @"boxCaptcityDesc";
    lplv.selectedIndex = _selectedIndex2;
    lplv.delegate = self;
    [lplv showInView:self.view animated:YES];

}

- (IBAction)showCanlendar:(id)sender {
    self.pmCC = [[PMCalendarController alloc] init];
    pmCC.delegate = self;
    pmCC.mondayFirstDayOfWeek = YES;
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat : @"yyyy-MM-dd"];
    pmCC.period = [PMPeriod oneDayPeriodWithDate:[formatter dateFromString:diningDate]];
    
    [pmCC presentCalendarFromView:sender
         permittedArrowDirections:PMCalendarArrowDirectionAny
                         animated:YES];
    pmCC.allowsPeriodSelection = YES;
    /*[pmCC presentCalendarFromRect:[sender frame]
     inView:[sender superview]
     permittedArrowDirections:PMCalendarArrowDirectionAny
     animated:YES];*/
    [self calendarController:pmCC didChangePeriod:pmCC.period];

}

#pragma mark PMCalendarControllerDelegate methods

- (void)calendarController:(PMCalendarController *)calendarController didChangePeriod:(PMPeriod *)newPeriod
{
    tbDate.text = [NSString stringWithFormat:@"就餐日期：%@", [newPeriod.endDate dateStringWithFormat:@"yyyy-MM-dd"]];
    NSString *d = [newPeriod.endDate dateStringWithFormat:@"yyyy-MM-dd"];
    if (![diningDate isEqualToString:d]) {
        diningDate = [d copy];
        [[calendarController view ] removeFromSuperview];
    }
}

- (IBAction)showSearch:(id)sender {
    BoxSearchViewController  *view = [[BoxSearchViewController alloc] initWithNibName:@"BoxSearchViewController" bundle:nil];
    view.cityId=cityId;
    view.areaId = areaId;
    view.diningDate = diningDate;
//    NSLog(@"%@",diningDate);

    view.diningTime = diningTime;
    view.boxType = boxType;
    view.capacity = capacityId;
    view._selectedTypeIndex = _selectedTypeIndex;
    view._selectedIndex = _selectedIndex;
    NSString * areaName = [[arrayArea objectAtIndex:_selectedIndex] objectForKey:@"areaName"];
    view.areaName =areaName;
    view.hidesBottomBarWhenPushed=YES;
	[self.navigationController pushViewController:view animated:YES];
//	[view release];
}
@end
